<?php //$Id: db_select.php,v 1.1.1.1 2014/08/23 06:57:06 ymlam Exp $ Copyright (C) 2014 Link2Tek LLC ?>
<?php

/**
 * Process database select with statement specified by 'query=' in querystring.
 * It operates in a session.
 *
 * Return XML depends on the type of query.
 * 
 * For SELECT, the returned XML is of the form:
 *   <result>
 *     <count>number</count>
 *     <row><column1>value1</column1>...</row>
 *     ...
 *   </result>
 *
 * For INSERT, UPDATE, REPLAE, OR DELETE, the returned XML is of the form:
 *   <result>
 *     <count>number</count>
 *   </result>
 * 
 * or in case of error
 *
 *   <result>
 *     <error>...</error>
 *   </result>
 *
 * If the name of the data item is "count(*)", it is replaced by "__count__".
 * With the exception of "count(*)", all select items must be 
 * table column names.
 */

include_once dirname(__FILE__)."/../_include/db.php";
include_once dirname(__FILE__)."/../_include/logging.php";
include_once dirname(__FILE__)."/../_include/config.php";

LoggerNDC::push("db_select.php");

try
{
  if (!isset($_GET['query']))
  {
    throw new Exception("query not set in querystring");
  }
  $query = trim($_GET['query']);
  $logger->info("sql: $query");
  
  // Handling depends on the command in the query 
  $words = explode(' ', trim($query));
  $queryType = strtoupper($words[0]);
  switch ($queryType)
  {
    case 'SELECT':
      $result = mysql_query($query);
      if (!$result)
      {
        throw new Exception("Failed $query - " . mysql_error());
      }
      $count = mysql_num_rows($result);
      $logger->info("SELECT obtained $count rows");
      
      // Excluding top-level node <result>
      $xmlContent = "<count>$count</count>\r\n";
      while($row = mysql_fetch_array($result, MYSQL_ASSOC))
      {
        $xmlContent .= "<row>";
        foreach ($row as $key=>$value)
        {
          if ($key=='count(*)') $key="__count__";
          $xmlContent .= "<$key>".htmlentities($value, ENT_NOQUOTES)."</$key>";
        }
        $xmlContent .= "</row>\r\n";
      }
      break;
  
/* Suppont only SELECT
    case 'INSERT':
    case 'UPDATE':
    case 'REPLACE':
    case 'DELETE':
      if (!mysql_query($query))
      {
        throw new Exception("Failed $query - " . mysql_error());
      }
      $count = mysql_affected_rows();
      $logger->info("$queryType affeced $count rows");
      $xmlContent = "<count>$count</count>\r\n";
      break;
*/
   
    default:
      throw new Exception("Query $queryType not supported");
  }
}
catch (Exception $e)
{
  $xmlContent = '<error>'.htmlentities($e->getMessage()).'</error>';
}
$returnStr = "<result>$xmlContent</result>";
$logger->info("Returning: $returnStr");
echo $returnStr;
?>

